#!/usr/bin/env python
#coding=utf-8
#########################################################
# File Name: python_systeminfo.py
# Author: Henson
# Created Time: 2016-11-20
# Email: 605998410@qq.com
#########################################################

green="\033[92m"
green_back="\033[42m"
red="\033[91m"
red_back="\033[41m"
blue="\033[94m"
purple="\033[95m"
end="\033[0m"


import psutil, time, re, sys, os
import commands
import socket
import urllib2
import platform
import pycurl
import StringIO
from IPy import IP
import dns.resolver
import getopt

#################################################################
#获取外网ip地址
class Get_public_ip:
    def getip(self):
        try:
            myip = self.visit("http://ip.chinaz.com/getip.aspx")
        except:
            try:
                myip = self.visit("http://ipv4.icanhazip.com/")
            except:
                myip = "So sorry!!!"
        return myip
    def visit(self,url):
        opener = urllib2.urlopen(url)
        if url == opener.geturl():
            str = opener.read()
        return re.search('\d+\.\d+\.\d+\.\d+',str).group()
g = Get_public_ip()


#显示系统所有硬件信息
def system_info():
    version = commands.getoutput("cat /etc/redhat-release")
    user_name = commands.getoutput("whoami")
    mem = psutil.virtual_memory()
    cpu_model = commands.getoutput("awk -F: '/model name/{print $2}' /proc/cpuinfo|awk 'NR==1'|sed 's/^ //'")
    cpu = psutil.cpu_count()
    Boot = time.strftime('%Y-%m-%d %H:%M:%S',time.localtime(psutil.boot_time()))
    mem_total = mem.total/1024/1024
    #mem_use = mem.used/1024/1024
    mem_use = commands.getoutput("free -h|awk '/buffers\/cache/ {print $3}'")
    #mem_free = mem.free/1024/1024
    mem_free = commands.getoutput("free -h|awk '/buffers\/cache/ {print $4}'")
    swap =commands.getoutput("free -h | awk '/Swap/ {print $2}'")
    #host_name = commands.getoutput("hostname")
    #host_name = socket.gethostname()
    host_name = platform.node()
    ip_address = commands.getoutput("ifconfig")
    ssh_connection= commands.getoutput("printenv SSH_CONNECTION |awk '{print $1}'")
    #ip_address = socket.gethostbyname(host_name)
    uptime = commands.getoutput("uptime |awk '{print $3 $4 $5}'")
    load = commands.getoutput("uptime |awk '{print $(NF-2),$(NF-1),$NF}'")
    linking = commands.getoutput("netstat -antp |grep -v 'established'|awk '{print $6}'|sort |uniq -c|sort -rn|xargs")
    login_count = commands.getoutput("w |grep pts|wc -l")
    network_card = commands.getoutput("ifconfig |awk -F'[ ]' '{print $1}'|xargs |column -t")
    cpu_Utilization = psutil.cpu_percent(interval=1)
    disk_Utilization = psutil.disk_usage('/').percent

    print
    print green+("System_Info".center(60,"*"))+end
    print
    print "Version              :",red+ version +end
    print "Username             :",red+ user_name +end
    print "HostName             :",red+ host_name +end
    print "Local IP             :",red+ re.search("(?<=inet addr:).*(?=\s+B)",ip_address).group()+end
    print "SSH Connection       :",red+ ssh_connection +end
    #print "Local IP             :",red+ ip_address +end
    print "Public IP            :",red_back+ g.getip() +end
    print "Cpu model            :",red+ cpu_model +end
    print ("Number of cores      :"+red+" %d"+end) %cpu
    print ("Total amount of mem  :"+red+" Mem_total={0}  Use={1}  Free={2}"+end).format(mem_total ,mem_use, mem_free)
    print ("Total amount of swap :"+red+" Total={}"+end).format(swap)
    print "system boot time     :",red+ Boot +end
    print "SystemRunningTime    :",red+ uptime +end
    print "Load average         :",red_back+ load +end
    print "Linking count        :",red_back+ linking +end
    print ("SSH logon count      :"+red+" [ {} ]"+end ).format(login_count)
    print ("Network card         :"+red+" [ {} ]"+end).format(network_card)
    print ("Cpu Utilization      :"+red+" [ {}% ]" +end).format(cpu_Utilization)
    print ("Disk / Utilization   :"+red+" [ {}% ]" +end).format(disk_Utilization)
    print
    print green+("System_Info".center(60,"*"))+end

###############################################################
#使用pycurl模块显示网站信息
class WebAndDns():
    def __init__(self, url):
        self.url = url

    def web_info(self):
        request = urllib2.Request(self.url)
        try:
            result = urllib2.urlopen(request)
            print "http status: ",result.getcode()
            print result.info()
        except urllib2.URLError, e:
            print e.reason

    def web_pycurl(self):
        str = StringIO.StringIO()
        #self.url = raw_input(green+"Please enter the Website ['q'=quit]: "+end)
        c = pycurl.Curl() # 创建一个 Curl 对象
        c.setopt(pycurl.URL, self.url) # 定义请求的 URL 常量
        c.setopt(pycurl.CONNECTTIMEOUT, 5) # 定义请求连接的等待时间
        c.setopt(pycurl.TIMEOUT, 5) # 定义请求超时时间
        c.setopt(pycurl.NOPROGRESS, 1) # 屏蔽下载进度条
        c.setopt(pycurl.FORBID_REUSE, 1) # 完成交互后强制断开连接，不重用
        c.setopt(pycurl.MAXREDIRS, 1) # 指定 HTTP 重定向的最大数为 1
        c.setopt(pycurl.DNS_CACHE_TIMEOUT,30) # 设置保存 DNS 信息的时间为 30 秒
        c.setopt(pycurl.WRITEFUNCTION,str.write)
        c.setopt(pycurl.FOLLOWLOCATION,1)
        try:
            if self.url == 'q':
                print "Good bye!\n"
                sys.exit()

            c.perform()  #提交请求
        except Exception,e:
            print "connecion error:",e
            print
            sys.exit()

        HTTP_CODE = c.getinfo(c.HTTP_CODE) # 获取 HTTP 状态码
        NAMELOOKUP_TIME = c.getinfo(c.NAMELOOKUP_TIME) # 获取 DNS 解析时间
        CONNECT_TIME = c.getinfo(c.CONNECT_TIME) # 获取建立连接时间
        PRETRANSFER_TIME = c.getinfo(c.PRETRANSFER_TIME) # 获取从建立连接到准备传输所消耗的时间
        STARTTRANSFER_TIME = c.getinfo(c.STARTTRANSFER_TIME) # 获取从建立连接到传输开始消耗的时间
        TOTAL_TIME = c.getinfo(c.TOTAL_TIME) # 获取传输的总时间
        SIZE_DOWNLOAD = c.getinfo(c.SIZE_DOWNLOAD) # 获取下载数据包大小
        HEADER_SIZE = c.getinfo(c.HEADER_SIZE) # 获取 HTTP 头部大小
        SPEED_DOWNLOAD=c.getinfo(c.SPEED_DOWNLOAD) # 获取平均下载速度

        print
        print red+("".center(50,">"))+end;print
        print ("HTTP 状态码：    "+green+"%s"+end) %HTTP_CODE
        print ("DNS 解析时间：   "+green+"%.2f ms"+end) %(NAMELOOKUP_TIME * 1000)
        print ("建立连接时间：   "+green+"%.2f ms"+end) %(CONNECT_TIME * 1000)
        print ("准备传输时间：   "+green+"%.2f ms"+end) %(PRETRANSFER_TIME * 1000)
        print ("传输开始时间：   "+green+"%.2f ms"+end) %(STARTTRANSFER_TIME * 1000)
        print ("传输结束总时间： "+green+"%.2f ms"+end) %(TOTAL_TIME * 1000)
        print ("下载数据包大小： "+green+"%d bytes/s"+end) %(SIZE_DOWNLOAD)
        print ("HTTP 头部大小：  "+green+"%d byte"+end) %(HEADER_SIZE)
        print ("平均下载速度：   "+green+"%d bytes/s"+end) %(SPEED_DOWNLOAD)
        print ("对应的真实地址： "+green+"%s"+end) %(c.getinfo(pycurl.EFFECTIVE_URL))

    ##############################################################
    #实现A记录查询方法
    def dns_A(self):
        #domain = raw_input("Please input an domain: ")
        A = dns.resolver.query(self.url,'A')
        print ("\n实现A记录查询:")
        for i in A.response.answer:
            for (num,j) in enumerate(i,1):
                print("{:d}: {:s}".format(num, j.address))

#上面class的主函数调用
def web_main():
    url = WebAndDns(raw_input(green+"Please enter the Website ['q'=quit]: "+end))
    url.web_info()
    url.web_pycurl()
    url.dns_A()

###############################################################
#将文件属性中的时间改为‘2011-1-12_00：00：00格式'
def formattime(localtime):
    endtime = time.strftime("%Y-%m-%d_%H:%M:%S", time.localtime(localtime))
    return endtime

def searchdir(arg,dirname,names):
    for filespath in names:
        #得到文件路径
        fullpath = os.path.join(dirname,filespath)
        #得到文件属性
        statinfo=os.stat(fullpath)
        #文件大小
        sizefile = statinfo.st_size
        #创建时间
        creattime = formattime(statinfo.st_ctime)
        #修改时间
        maketime = formattime(statinfo.st_mtime)
        #浏览时间
        readtime = formattime(statinfo.st_atime)
        #判断是文件夹还是文件
        if os.path.isdir(fullpath):
            filestat = 'DIR'
        else:
            filestat = 'FILE'
            #with open('/tmp/new_file','a') as f:
            #    for i in f:
            #        i.write('【%s】路径：%s 文件大小(B)：%s 创建时间：%s 修改时间：%s 浏览时间：%s\r\n'%(filestat,fullpath,sizefile,creattime,maketime,readtime))
            open ('/tmp/new_file.txt','a').write('[%s]路径：%s 大小(B)：%s 创建：%s 修改：%s 浏览：%s\r\n'%(filestat,fullpath,sizefile,creattime,maketime,readtime))
    os.system("cat /tmp/new_file.txt |column -t > /tmp/new_file1.txt")

def main_searchdir():
    #paths="/home/python/"
    while 1:
        print
        print red+("美丽的分割线".center(50,"="))+end
        print "Current path name: [ {0} ] ".format(commands.getoutput("pwd"))
        print
        paths = raw_input(green+"Please input the pathname ['q'=exit]: "+end)
        if paths == '' or paths == 'q':
            #print "string not null"
            sys.exit()
        #elif paths == 'q':
        #    print "Goodbye!"
        #    sys.exit()

        os.system("> /tmp/new_file.txt")
        os.path.walk(paths,searchdir,())
        #os.system("cat /tmp/new_file.txt |column -t > /tmp/new_file.txt")

        with open("/tmp/new_file1.txt") as f:
            for (num,item) in enumerate(f,1):
                print "{0}: {1}".format(num,item).strip()

###########################################################
#使用IPY模块，根据输入的 IP 或子网返回网络、掩码、广播、反向解析、子网数、IP 类型等信息
def IP_S():
    num = 0
    while num < 3:
        print("="*50)
        ip_s = raw_input(green+"Please input an IP or net-range: "+end)
        ips = IP(ip_s)
        try:
            if len(ips) > 1:
                print(("Net: "+red+"{}"+end).format(ips.net()))
                print(("Netmaks; "+red+"{}"+end).format(ips.netmask()))
                print(("Broadcast: "+red+"{}"+end).format(ips.broadcast()))
                print(("Reverse address: "+red+"{}"+end).format(ips.reverseNames()[0]))
                print(("Subnet: "+red+"{}"+end).format(len(ips)))
                print(("Version: "+red+"{}"+end).format(ips.version()))

            else:
                print(("Reverse address: "+red+"{}"+end).format(ips.reverseNames()[0]))
                print(("Subnet: "+red+"{}"+end).format(len(ips)))

            print(("Hexadecimal: "+red+"{}"+end).format(ips.strHex()))
            print(("Binary ip: "+red+"{}"+end).format(ips.strBin()))
            print(("Iptype: "+red+"{}"+end).format(ips.iptype()))
            print("\n")
        except KeyboardInterrupt,e:
            print (e)
        num += 1


###########################################################
#批量修改文件后缀脚本如(.txt .bat)
def rename(path, old_extension, new_extension):
    for (path, dirs, files) in os.walk(path):
        for filename in files:
            extension_name = os.path.splitext(filename)[1]
            if (cmp(extension_name, old_extension)==0):
                newname = filename.replace(old_extension, new_extension)
                old_path = path + "/" + filename
                new_path = path + "/" + newname
                print "\nResult:"
                print "old_path:" + old_path + ""
                print "new_path:" + new_path + ""
                try:
                    os.rename(old_path, new_path)
                except ValueError:
                    print "Error when rename the file " + old_path
                except NameError:
                    print "Error when rename the file " + old_path
                except OSError:
                    print new_path + " The file is already exist!"

def main_rename():
    print red+("".center(50,">"))+end
    print"PATH: {}".format(commands.getoutput('pwd'))
    os.system("ls")
    print
    print red+("".center(50,">"))+end
    Path_name = raw_input("Please input the path name : ")
    Old_postfix = raw_input("Please input the old postfix : ")
    New_postfix = raw_input("Please input the new postfix : ")
    rename(Path_name, Old_postfix, New_postfix)


###########################################################
#def usage():
#    print("Usage:%s [-a|-o|-c] [--help|--output] args...." %Dsys.argv[0])

def Help():
    return '''
Usage:python script [OPTIONS]
    -h, --help      Show help
    -s, --system    Show system all info
    -w, --web       Show website info
    -f, --file      Show file (path ,size, change, browse) info
    --ip            Show (net, subnet, mask, binary, reverse address...) info
    --rename        Modify the file suffix script (.txt .bak)
'''

######################################################
#主程序
def main():
    try:
        opts, args = getopt.getopt(sys.argv[1:],
                'wshf',
                ['help', 'web', 'system', 'file','ip','rename','output=']
                )
    except getopt.GetoptError:
        pass
    #for name, value in opts:
    #    print name, value
    #for item in args:
    #    print item

    for (opt, arg) in opts:
        if opt in ['-s', '--system']:
            system_info();print
            #sys.exit()
        elif opt in ['-w', '--web']:
            while 1:
                print ;print red+(''.center(50,'<'))+end
                web_main()
        elif opt in ['-h', '--help']:
            print (purple+"{0}"+end).format(Help())
        elif opt in ['-f', '--file']:
            main_searchdir()
        elif opt in ['--ip']:
            IP_S()
        elif opt in ['--rename']:
            main_rename()

if __name__ == "__main__":
    main()